<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace plugins\tools\controller; //Demo插件英文名，改成你的插件英文就行了
use cmf\controller\PluginBaseController;
use think\Db;

class TinyurlsController extends PluginBaseController
{
    /**
     * 批量短链接还原
     */
    function rollback()
    {
        return $this->fetch("/tinyurls_rollback");
    }

    
    public function rollbackPost()
    {
        if ($this->request->isPost()) {
            
            $result = $this->validate($this->request->param(), 'Tinyurls');
            $compact_urls  = htmlspecialchars_decode($this->request->param('compact_urls'));
            
            $match_times = preg_match_all('/http(s)?:\/\/[a-zA-Z|\d]+\.[a-zA-Z|\d]+\/([a-zA-Z|\d|\-|\+|_\.\/\?%=#]*)?/', $compact_urls, $matches);

            if($match_times) {
                $short_urls = $matches[0];
                foreach($short_urls as $url)
                {
                    $headers = @get_headers($url, 1);
                
                    if(strpos($headers[0],'302') || strpos($headers[0],'301'))
                    {
                        $replace = is_array($headers['Location'])? $headers['Location'][0]: $headers['Location']; 
                        $compact_urls = str_replace($url, $replace, $compact_urls);
                    }
                
                }
            }
            
            if ($result !== true) {
                // 验证失败 输出错误信息
                $this->error($result);
            } else {
                //$result = DB::name('crawler_rule')->where(['id' => $id])->update($data);
                if ($result !== false) {
                    $this->success("保存成功！",'',['compact_urls' => $compact_urls]);
                } else {
                    $this->error("保存失败！");
                }
            }

        }
    }

}


